{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "baef4ff5-976e-4070-a03c-ebb56cf5f8cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.feature_extraction.text import TfidfVectorizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ffe373fc-6e58-49a4-a2ca-5a71d1897c61",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['beijing' 'chinese' 'japan' 'macao' 'shanghai' 'tokyo']\n"
     ]
    }
   ],
   "source": [
    "# 实例化tf实例\n",
    "tv = TfidfVectorizer(use_idf=True,smooth_idf=True,norm=None)\n",
    "\n",
    "# 输入训练集矩阵，每行表示一个文本\n",
    "train = [\"Chinese Beijing Chinese\",\n",
    "         \"Chinese Chinese Shanghai\",\n",
    "         \"Chinese Macao\",\n",
    "         \"Tokyo Japan Chinese\"]\n",
    "# 训练，构建词汇表以及词项idf值，并将输入文本列表转成VSM矩阵形式\n",
    "tv_fit = tv.fit_transform(train)\n",
    "# 查看一下构建的词汇表\n",
    "print(tv.get_feature_names_out())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6efa444a-ecd8-419d-a957-1f1bda8732c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1.91629073 2.         0.         0.         0.         0.        ]\n",
      " [0.         2.         0.         0.         1.91629073 0.        ]\n",
      " [0.         1.         0.         1.91629073 0.         0.        ]\n",
      " [0.         1.         1.91629073 0.         0.         1.91629073]]\n"
     ]
    }
   ],
   "source": [
    "# 查看输入文本列表的VSM矩阵\n",
    "print(tv_fit.toarray())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98fff546-d05c-401c-a7a8-64dba9aea5c7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
